#include"get_id.h"
#include"select_id.h"

const char *express_no=NULL;
 char *warehouse=NULL;
 sqlite3 *db1 =NULL;

 int main(void) {
    printf("ThingsCloud 数据监控程序启动 (每8秒更新一次)\n");
 
    // 初始化libcurl全局环境
    curl_global_init(CURL_GLOBAL_DEFAULT);
      // 数据库初始化
    if (sql_init(&db1))
    {
        printf("17：sqlite3_init error\n");
        return -1;
    }
    // 循环发送请求，每8秒一次
    while (1) {
        char *buf=NULL;

        if(0==send_request())
        {
            printf("main_express_no: %s\n",express_no);
            printf("main_仓库: %s\n",warehouse);
            if(express_no == NULL || strcmp(express_no, "(null)") == 0)
            {
                printf("express_no is null;\n");
                sleep(8);
                continue;
            }
            if(0!=select_from(express_no,db1))
            {
                printf("this id in sqlite3d\n");
                sleep(8);
                continue;
            }
           buf= select_id(express_no);
           printf("get_id main %s\n",buf);

           if(strlen(buf)>1){
            insert_information(express_no,warehouse,buf,db1);
           }else{
            printf("未查询到信息\n");
           }
        }
        sleep(8);
    }

    // 清理全局资源（实际不会执行到这里，因为上面是无限循环）
    curl_global_cleanup();
    return 0;
}
// 回调函数，用于处理HTTP响应数据
size_t write_callback(void *contents, size_t size, size_t nmemb, void *userp) 
{
    size_t realsize = size * nmemb;
    char **response = (char**)userp;

    // 重新分配内存以容纳新收到的数据
    *response = realloc(*response, strlen(*response) + realsize + 1);
    if (*response == NULL) {
        fprintf(stderr, "内存分配失败\n");
        return 0;
    }

    // 将新数据追加到响应缓冲区
    strncat(*response, (char*)contents, realsize);
    return realsize;
}

// 解析JSON响应并打印温度和光照数据
void parse_and_print_response(const char *response) {
    struct json_object *root = json_tokener_parse(response);
    if (root == NULL) {
        fprintf(stderr, "解析JSON失败\n");
        return;
    }

    // 获取当前时间并打印
    time_t now;
    time(&now);
    printf("\n[%s] 数据更新:\n", ctime(&now));

    // 获取result字段
    struct json_object *result_obj;
    if (json_object_object_get_ex(root, "result", &result_obj)) {
        int result = json_object_get_int(result_obj);
        printf("请求结果: %d (1表示成功)\n", result);
    }

    // 获取attributes字段
    struct json_object *attributes_obj;
    if (json_object_object_get_ex(root, "attributes", &attributes_obj)) {
        // 获取ID
        struct json_object *num_obj;
        if (json_object_object_get_ex(attributes_obj, "TrackingCode", &num_obj)) {
            printf("express_No: %s\n", json_object_get_string(num_obj));
             express_no = strdup(json_object_get_string(num_obj));
        } else {
            printf("未找到express_No\n");
        }

        // 获取store_house
        struct json_object *house_obj;
        if (json_object_object_get_ex(attributes_obj, "warehouse", &house_obj)) {
            printf("仓库: %s\n", json_object_get_string(house_obj));
            warehouse=strdup(json_object_get_string(house_obj));
        } else {
            printf("未找到仓库\n");
        }
    } else {
        printf("未找到属性数据\n");
    }

    json_object_put(root); // 释放JSON对象
}

// 发送HTTP请求并处理响应
int send_request() {
    CURL *curl;
    CURLcode res;
    char *response = malloc(1); // 初始化为空字符串
    if (response == NULL) {
        fprintf(stderr, "内存分配失败\n");
        return 1;
    }
    response[0] = '\0';

    // 初始化libcurl
    curl = curl_easy_init();
    if (curl) {
        // 设置请求URL
        const char *url = "http://sh-1-api.iot-api.com/device/v1/brqqr11kdowdp945/attributes?keys=TrackingCode,warehouse";
        
        // 设置请求头
        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers, "Content-Type: application/json");
        headers = curl_slist_append(headers, "Project-Key: WlikZCzmpM");
        
        // 设置curl选项
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
        curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10L); // 设置10秒超时
        
        // 执行HTTP请求
        res = curl_easy_perform(curl);
        
        // 检查请求是否成功
        if (res != CURLE_OK) {
            fprintf(stderr, "请求失败: %s\n", curl_easy_strerror(res));
        } else {
            // 解析并打印结果
            parse_and_print_response(response);
        }

        // 清理资源
        curl_slist_free_all(headers);
        curl_easy_cleanup(curl);
    }

    // 清理内存
    free(response);
    return 0;
}

//向数据库中插入信息
void insert_information(const char *express_no,char * warehouse,char  *buf,sqlite3 *db)
{
    char sql[128]={0};
    char *errmsg = NULL;
    sprintf(sql,"insert into information(id,mesg,storehouse)values('%s','%s','%s');",express_no,buf,warehouse);
if (0 != sqlite3_exec(db, sql, NULL, NULL, &errmsg))
        {
            fprintf(stderr, "SQL insert error: %s\n", errmsg);
            sqlite3_free(errmsg); // 必须释放错误消息内存
            return;
        }
        printf("insert success!\n");
}
//判断是否存在数据库中
int select_from(const char *express_no,sqlite3 *db)
{
       char sql[128]={0};
       char *errmsg = NULL;
    int nrow, ncolumn;
    char **resultp = NULL;
     sprintf(sql, "select * from information where id='%s'",express_no);
    if (0 != sqlite3_get_table(db, sql, &resultp, &nrow, &ncolumn, &errmsg))
    {
        fprintf(stderr, "SQL select_inform144 error: %s\n", errmsg);
        sqlite3_free(errmsg); // 必须释放错误消息内存
        return -1;
    }
    else if (nrow ==1)
    { // id已存在
        return -1;
    }
    return 0;

}

int sql_init(sqlite3 **db)
{
    /*数据库初始化*/
    if (0 != sqlite3_open("user.db", db))
    {
        fprintf(stderr, "sqlite3_open: %s\n", sqlite3_errmsg(*db));
        return -1;
    }
    /*执行sql语句: 创建信息表*/
    char *errmsg = NULL;
    char sql[128] = "create table if not exists information(id primary key, mesg text,storehouse text)";
    if (0 != sqlite3_exec(*db, sql, NULL, NULL, &errmsg))
    {
        fprintf(stderr, "sqlite3_exec: %s\n", errmsg);
        return -1;
    }
    printf("create information success!\n");

    return 0;
}
